﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ArchivingDataModel;
using ArchivingDataWebForms.Helpers;
using Telerik.Web.UI;
using WebHelper.Handlers;

namespace ArchivingDataWebForms.Pages.Folders
{
    public partial class AddFolder : WebFormBase
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            using (ArchivingDataEntities ent = new ArchivingDataEntities())
            {
                if (!this.IsPostBack)
                {
                    this.getFilesTypes();
                    // existing folder (bind to controls)
                    if (!string.IsNullOrEmpty(this.Request.QueryString[QueryStringParams.Folder_ID]))
                    {
                        long folderID = Convert.ToInt64(this.Request.QueryString[QueryStringParams.Folder_ID]);

                        var currentFolder = ent.Folders.FirstOrDefault(i => i.Folder_ID == folderID);
                        this.ImageFolder.ImageUrl = currentFolder.ImagePath;
                        this.RadTextBoxCode.Text = currentFolder.Folder_Code;
                        this.RadTextBoxName.Text = currentFolder.FolderName_Ar;
                        this.RadTextBoxNote.Text = currentFolder.FolderNote_Ar;
                        this.RadButtonRecycleBin.Checked = currentFolder.Is_RecycleBin.Value;
                        currentFolder.FilesTypeReference.Load();
                        if (currentFolder.FilesType != null)
                        {
                            this.RadComboBoxListFilesType.SelectedValue = currentFolder.FilesType.FileType_ID.ToString();
                        }
                        currentFolder.FolderProperties.Load();
                    }
                }
            }
        }
        protected void RadButtonSave_Click(object sender, EventArgs e)
        {
            try
            {
                using (ArchivingDataEntities ent = new ArchivingDataEntities())
                {
                    long? currentID=null;
                    //insert
                    if (string.IsNullOrEmpty(this.Request.QueryString[QueryStringParams.Folder_ID]))
                    {
                        long? parentId = null;
                        if (!string.IsNullOrEmpty(this.Request.QueryString[QueryStringParams.Parent_ID]))
                        {
                            parentId = Convert.ToInt64(this.Request.QueryString[QueryStringParams.Parent_ID]);
                        }
                        long? fileTypeID = null;
                        if (!string.IsNullOrEmpty(this.RadComboBoxListFilesType.SelectedValue))
                        {
                            fileTypeID = Convert.ToInt64(this.RadComboBoxListFilesType.SelectedValue);
                        }
                        Folder newFolder = new Folder()
                        {
                            Folder_Code = this.RadTextBoxCode.Text,
                            ParentFolder_ID = parentId,
                            Folder_Order = ent.Folders.Where(i => i.ParentFolder_ID == parentId).Count() + 1,
                            FolderName_Ar = this.RadTextBoxName.Text,
                            FolderNote_Ar = this.RadTextBoxNote.Text,
                            Is_RecycleBin = this.RadButtonRecycleBin.Checked,
                            FilesType = ent.FilesTypes.FirstOrDefault(i => i.FileType_ID == fileTypeID)
                        };
                        if (parentId == null)
                        {
                            newFolder.Folder_Order = ent.Folders.Count() + 1;
                        }
                        var items = ent.Folders.Where(i => i.ParentFolder_ID == parentId);
                        newFolder.Folder_UniqueText = WebHelper.Helpers.StringHelper.ToUniqueStatement(newFolder.Folder_Code + newFolder.FolderName_Ar + newFolder.FolderNote_Ar + newFolder.FolderNote_Ar + newFolder.FolderNote_En);
                        ent.AddToFolders(newFolder);
                        ent.SaveChanges();
                        currentID = newFolder.Folder_ID;
                        string imagePath = CustomAppSettings.DefaultFolderImagePath;
                        if (this.RadAsyncUploadImage.UploadedFiles.Count > 0)
                        {
                            imagePath = CustomAppSettings.FoldersImagesPath + "/" + newFolder.Folder_ID + this.RadAsyncUploadImage.UploadedFiles[0].GetExtension();
                            Directory.CreateDirectory(Path.GetDirectoryName(CustomAppSettings.getActualPath(imagePath)));
                            this.RadAsyncUploadImage.UploadedFiles[0].SaveAs(CustomAppSettings.getActualPath(imagePath));
                        }
                        newFolder.ImagePath = imagePath;
                    }
                    //update
                    else
                    {
                        long folderID = Convert.ToInt64(this.Request.QueryString[QueryStringParams.Folder_ID]);
                        currentID = folderID;
                        Folder currentFolder = ent.Folders.FirstOrDefault(i => i.Folder_ID == folderID);
                        currentFolder.Folder_Code = this.RadTextBoxCode.Text;
                        long? fileTypeID = null;
                        if (!string.IsNullOrEmpty(this.RadComboBoxListFilesType.SelectedValue))
                        {
                            fileTypeID = Convert.ToInt64(this.RadComboBoxListFilesType.SelectedValue);
                        }
                        currentFolder.FolderName_Ar = this.RadTextBoxName.Text;
                        currentFolder.FolderNote_Ar = this.RadTextBoxNote.Text;
                        currentFolder.Is_RecycleBin = this.RadButtonRecycleBin.Checked;
                        currentFolder.FilesType = ent.FilesTypes.FirstOrDefault(i => i.FileType_ID == fileTypeID);

                        currentFolder.Folder_UniqueText = WebHelper.Helpers.StringHelper.ToUniqueStatement(currentFolder.Folder_Code + currentFolder.FolderName_Ar + currentFolder.FolderNote_Ar + currentFolder.FolderNote_Ar + currentFolder.FolderNote_En);
                        if (this.RadAsyncUploadImage.UploadedFiles.Count > 0)
                        {
                            string imagePath = CustomAppSettings.FoldersImagesPath + "/" + currentFolder.Folder_ID + this.RadAsyncUploadImage.UploadedFiles[0].GetExtension();
                            //remove prevois image Photo
                            if (currentFolder.ImagePath != CustomAppSettings.DefaultFolderImagePath)
                            {
                                System.IO.File.Delete(CustomAppSettings.getActualPath(currentFolder.ImagePath));
                            }
                            //save new photo
                            Directory.CreateDirectory(Path.GetDirectoryName(CustomAppSettings.getActualPath(imagePath)));
                            this.RadAsyncUploadImage.UploadedFiles[0].SaveAs(CustomAppSettings.getActualPath(imagePath));
                            currentFolder.ImagePath = imagePath;
                        }
                    }
                    ent.SaveChanges();
                    this.ShowNotification("لقد تم الحفظ", NotificationIconType.Ok);
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "RefreshParentTree", "window.parent.RefreshFolderTree('" + currentID + "')", true);
                    //string url= WebHelper.Helpers.UrlHelper.GetCompleteUri("~/Pages/Folders/ViewFolders.aspx?"+QueryStringParams.Folder_ID+"="+currentID);
                    //this.RedirectParent(url,1000);
                }
            }
            catch (Exception err)
            {
                this.ShowNotification("حدث الخطا التالي اثناء الحفظ " + err.Message, NotificationIconType.Error);
            }
        }
        protected void RadButtonDeleteImage_Click(object sender, EventArgs e)
        {
            try
            {
                using (ArchivingDataEntities ent = new ArchivingDataEntities())
                {
                    if (!string.IsNullOrEmpty(this.Request.QueryString[QueryStringParams.Folder_ID]))
                    {
                        long id = Convert.ToInt64(this.Request.QueryString[QueryStringParams.Folder_ID]);
                        var folder = ent.Folders.FirstOrDefault(i => i.Folder_ID == id);
                        //remove prevois image Photo
                        if (folder.ImagePath != CustomAppSettings.DefaultFolderImagePath)
                        {
                            System.IO.File.Delete(CustomAppSettings.getActualPath(folder.ImagePath));
                            folder.ImagePath = CustomAppSettings.DefaultFolderImagePath;
                            ent.SaveChanges();
                            this.ImageFolder.ImageUrl = CustomAppSettings.DefaultFolderImagePath;
                        }
                    }
                    this.RadAsyncUploadImage.UploadedFiles.Clear();
                }
            }
            catch (Exception er)
            {
                this.ShowNotification("حدث الخطا التالي  " + er.Message, NotificationIconType.Error);
            }
        }

        protected void getFilesTypes()
        {
            using (ArchivingDataEntities ent = new ArchivingDataEntities())
            {
                var filesTypes = ent.FilesTypes.OrderBy(i => i.FileTypeName_Ar).ToArray();
                this.RadComboBoxListFilesType.DataSource = filesTypes;
                this.RadComboBoxListFilesType.DataTextField = "FileTypeName_Ar";
                this.RadComboBoxListFilesType.DataValueField = "FileType_ID";
                this.RadComboBoxListFilesType.DataBind();
                if (filesTypes.Count() > 0)
                {
                    this.RadComboBoxListFilesType.SelectedValue = filesTypes[0].FileType_ID.ToString();
                }
            }
        }


    }
}